package fun.xming.memlib;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.internal.LinkedTreeMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import fun.xming.memlib.tools.MemManager;
import android.text.method.ScrollingMovementMethod;
import android.os.Handler;

public class RelearnActivity extends Activity {
	Boolean finished = false;
    String name;
    HashMap memory;
    String key,value;
    int now_mistake = 0;
    ArrayList<Integer> mistakes;
    Iterator<Map.Entry<String, LinkedTreeMap>> iterator;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_relearn);
		((TextView)findViewById(R.id.relearn_show)).setMovementMethod(ScrollingMovementMethod.getInstance());
        Intent intent = getIntent();
        mistakes = new ArrayList<>();
        name = intent.getStringExtra("name");
        memory = MainActivity.getMemManager().getMem(name);
        iterator = memory.entrySet().iterator();
        next();
    }
	

    private void tip(String tip) {
        ((TextView)findViewById(R.id.relearn_tip)).setText(tip);
    }

    private void pushShowLine(String line) {
        final TextView view = ((TextView)findViewById(R.id.relearn_show));
        final String text = String.valueOf(view.getText()) + "\n[] " + line;
        
        runOnUiThread(new Runnable() {
				@Override
				public void run() {
					view.setText(text);
					//==================add auto scroll========================
					//log View自动滚动
					view.post(new Runnable() {
							@Override
							public void run() {
								int scrollAmount = view.getLayout().getLineTop(view.getLineCount()) - view.getHeight();
								if (scrollAmount > 0)
									view.scrollTo(0, scrollAmount);
								else
									view.scrollTo(0, 0);
							}
						});
				}
			});
    }

    private boolean next() {
        if(iterator.hasNext()) {
            Map.Entry<String, LinkedTreeMap> e = iterator.next();
            key = e.getKey();
            value = String.valueOf(e.getValue().get("context"));
            tip("Please input the corresponding of [" + key + "]");
            return true;
        } else {
            return false;
        }
    }

    public void relearnSubmitOnClick(View view) {
		if(finished)
			return;
        EditText inputView = ((EditText)findViewById(R.id.relearn_input));
        String input = String.valueOf(inputView.getText());
		pushShowLine("You: "+input+"("+input.length()+")");
        if(input.equals(value)) {
            mistakes.add(now_mistake);
            pushShowLine("Good Job! You have answered MARVELLOUSLY Right. The mis-count is: "+(now_mistake));
            now_mistake = 0;
			inputView.setText("");
			inputView.setHint("Fill here");
            if(!next()) {
                finishQuestioning();
            }
        } else {
			if(++now_mistake >= value.length()) {
				mistakes.add(now_mistake);
				now_mistake = 0;
				pushShowLine("You stupid jerk! You have tried over all chances. The answer is: "+value+"("+value.length()+")");
				inputView.setText("");
				inputView.setHint("Fill here");
				if(!next()) {
					finishQuestioning();
				}
				return;
			}else {
				inputView.setHint(value.substring(0, now_mistake));
				inputView.setText("");
				//inputView.setSelection(inputView.getText().length());
				
			}
            pushShowLine("Ooooops! See you have f*king answered what shit!? Some tips are inputed.");
        }
    }
    public void finishQuestioning() {
		boolean pass = true;
        tip("(Re)Learning Over!");
		pushShowLine(">>>>>>>>>>>>>>>>>");
		pushShowLine("Your answers:");
        int i = 0;
		for(;i<mistakes.size();i++) {
			if(mistakes.get(i) >1) {
				pass = false;
			}
		}
        i = 0;
		if(pass) {
			for(Object o:memory.entrySet()) {
				Map.Entry<String,LinkedTreeMap> entry = (Map.Entry<String,LinkedTreeMap>)o;
				LinkedTreeMap<String,String> map = entry.getValue();

				key = entry.getKey();
				value = String.valueOf(entry.getValue().get("context"));
				Long now = System.currentTimeMillis();
				Long lastTime = map.get("last-time").equals("0") ? now : Long.valueOf(map.get("last-time"));
				map.put("last-time",String.valueOf(now));
				String misString = String.valueOf(map.get("last-mis-count"));
				String[] miss = misString.split(":");
				int misi = 0;
				for(int ii=0;ii<miss.length;ii++) {
					misi += Integer.valueOf(miss[i]);
				}
				misi /= miss.length;
				map.put("last-mis-count",String.valueOf(misi));
				Long deltaTime = (now - lastTime);
				map.put("S", String.valueOf(MemManager.calcNewMemQualty(deltaTime,Double.valueOf(map.get("S")),Integer.valueOf(map.get("last-mis-count")))));
				memory.put(key,map);
				pushShowLine(key+"("+value+")"+"Mis-time: "+mistakes.get(i)+"Average m-t: "+misi);
				i++;
			}
			tip("(Re)Learning Success!");
			pushShowLine("Your leaening has beem recorded. God bless you.");
		} else {
			for(Object o:memory.entrySet()) {
				Map.Entry<String,LinkedTreeMap> entry = (Map.Entry<String,LinkedTreeMap>)o;
				LinkedTreeMap<String,String> map = entry.getValue();

				key = entry.getKey();
				value = String.valueOf(entry.getValue().get("context"));
				//Long now = System.currentTimeMillis();
				//Long lastTime = map.get("last-time").equals("0") ? now : Long.valueOf(map.get("last-time"));
				//map.put("last-time",String.valueOf(now));
				String misString = String.valueOf(map.get("last-mis-count"));
				misString = misString + ":" + mistakes.get(i);
				map.put("last-mis-count",misString);
				//Long deltaTime = (now - lastTime);
				//map.put("S", String.valueOf(MemManager.calcNewMemQualty(deltaTime,Double.valueOf(map.get("S")),Integer.valueOf(map.get("last-mis-count")))));
				memory.put(key,map);
				pushShowLine(key+"("+value+")"+"Mistake time: "+mistakes.get(i));
				i++;
			}
			tip("(Re)Learning FAIL!");
			pushShowLine("Please turn back and RESTART relearning until the mis-count of each word is under 1 time");
		}
        MainActivity.getMemManager().setMem(name,memory);
		finished = true;
    }

}
